package com.lean.android.ad.core.splash

import android.os.Bundle
import androidx.activity.addCallback
import androidx.fragment.app.FragmentActivity
import com.lean.android.ad.core.Ad
import com.lean.android.ad.core.AdLoaders
import com.lean.android.ad.core.AdSdk
import com.lean.android.ad.repository.localcache.AdLocalCache
import com.lean.android.ad.utils.AdLog
import com.lean.android.ad.utils.StatusBarHelper
import java.lang.ref.WeakReference

class HotSplashAdLauncherActivity : FragmentActivity() {

    private lateinit var splashAdView: SplashAdView
    private var splashAdRef = WeakReference<Ad>(null)

    override fun onCreate(savedInstanceState: Bundle?) {
        com.lean.android.ad.utils.StatusBarHelper.translucent(this) //沉浸式
        super.onCreate(savedInstanceState)

        splashAdView = AdSdk.getAdConfig().splashAdView
        setContentView(splashAdView.createContentView(this))

        onBackPressedDispatcher.addCallback { }

        splashAdView.startProgressAnimation()


        AdLoaders.startSplashAd(this, splashAdView.findSplashContainer(), false, onAdLoaded = { ad ->
            splashAdRef = WeakReference(ad)
            AdSdk.splashAdManager.updateSplashAdState(SplashAdState.LoadSuccess(ad))
            AdLog.d(AdLog.AdSplashLoadTag, "hot splash ad onAdLoaded")
        }, onAdShow = {
            AdLog.d(AdLog.AdSplashLoadTag, "hot splash ad onAdShow")
            AdSdk.splashAdManager.updateSplashAdState(SplashAdState.Shown)
            AdLocalCache.splashAdShowTime = System.currentTimeMillis()
            splashAdView.cancelProgressAnimation()
        }, onAdFinished = {
            AdLog.d(AdLog.AdSplashLoadTag, "hot splash ad onAdFinished")
            AdSdk.splashAdManager.close()
            splashAdView.removeAllViewsInContainer()

            finish()
            AdLoaders.startInterstitialAd(this)
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        AdSdk.splashAdManager.updateSplashAdState(SplashAdState.Closed)
        splashAdRef.get()?.also {
            it.destroy()
        }
        splashAdRef.clear()
    }
}